import Deep from "./deep";

/*
 * @Descripttion: 
 * @version: 
 * @Author: Lee
 * @Date: 2020-05-25 15:02:52
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-05-27 14:48:46
 */
export default class Observer {
    constructor(data) {
        // 数据转存
        this.data = data;
        // 遍历对象完成所有数据的劫持
        this.walk(this.data)
    }

    /**
     * @name: 遍历对象
     * @test: test font
     * @msg: 
     * @param {type} 
     * @return: 
     */
    walk(data) {
        if (!data || typeof data !== "object") {
            return;
        }
        Object.keys(data).forEach(key => {
            this.defineReactive(data, key, data[key])
        });

    }


    /**
     * @name: 动态设置响应式数据
     * @test: test font
     * @msg: 
     * @param {type} 
     * @return: 
     */

    defineReactive(data, key, value) {
        let deep = new Deep();
        Object.defineProperty(data, key, {
            // 数据是否可以通过for-in来遍历
            enumerable: true,
            // 不可在配置
            configurable: false,
            get() {
                Deep.target && deep.addSub(Deep.target);
                return value;
            },
            set(newValue) {
                value = newValue;
                // todo 数据改变页面也发生改变
                deep.notify();
            }
        });
        // 使用递归 遍历二级对象
        this.walk(value);
    }
}